package com.lf.data;

import org.bson.types.ObjectId;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 严秋旺 on 2015/1/6.
 * <p/>
 * 数据簇
 */
public class Cluster extends HashMap<String, Object> {

    @Key(keyType = KeyType.MapKey, valueType = ValueType.String, check = Validate.OBJECTID, nullable = true)
    public static final String ID = "_id";

    public static final String CREATED = "created";

    public Cluster() {
        super();
    }

    public Cluster(Map<String, Object> map) {
        super(map);
    }

    public Cluster(String key, Object object) {
        super();
        put(key, object);
    }

    public void setId(String id) {
        this.put(ID, new ObjectId(id));
    }

    public String setId() {
        ObjectId oid = new ObjectId();
        this.put(ID, oid);
        return oid.toString();
    }

    public String getId() {
        return getString(ID);
    }

    public String getString(String key) {
        return getString(key, "");
    }

    public String getString(String key, String defval) {
        if (containsKey(key)) {
            return get(key).toString();
        } else {
            return defval;
        }
    }

    public int getInt(String key) {
        return getInt(key, 0);
    }

    public int getInt(String key, int defval) {
        if (containsKey(key)) {
            Object object = get(key);
            if (object instanceof Integer) {
                return (Integer) object;
            } else {
                try {
                    return Integer.parseInt(object.toString());
                } catch (Exception e) {
                    return defval;
                }
            }
        } else {
            return defval;
        }
    }

    public List<Object> getList(String key) {
        if (containsKey(key)) {
            return (ArrayList<Object>) get(key);
        } else {
            return new ArrayList<>();
        }
    }

    public Map<String, Object> getMap(String key) {
        if (containsKey(key)) {
            return (Map<String, Object>) get(key);
        } else {
            return new HashMap();
        }
    }

    public void putEl(String elKey, Object value) {

    }

}
